package com.hatricks.is.algorithm.abc;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;

import java.util.concurrent.Semaphore;

public class PrintABC {

    private static final Semaphore semA = new Semaphore(1); // a线程可以立刻执行
    private static final Semaphore semB = new Semaphore(0); // b线程需要等a执行
    private static final Semaphore semC = new Semaphore(0); // c线程需要等b执行

    public static void main(String[] args) {
        Thread threadA = new Thread(new PrintTask("a", semA, semB));
        Thread threadB = new Thread(new PrintTask("b", semB, semC));
        Thread threadC = new Thread(new PrintTask("c", semC, semA));

        threadA.start();
        threadB.start();
        threadC.start();

    }

    static class PrintTask implements Runnable {
        private String letter;
        private Semaphore currentSemaphore;
        private Semaphore nextSemaphore;

        public PrintTask(String letter, Semaphore currentSemaphore, Semaphore nextSemaphore) {
            this.letter = letter;
            this.currentSemaphore = currentSemaphore;
            this.nextSemaphore = nextSemaphore;
        }

        @Override
        public void run() {
            try {
                while (true) {
                    // 当前线程获取许可并打印
                    currentSemaphore.acquire();
                    System.out.println(StrUtil.format("当前的线程Id为:[{}] 当前运行的字母为:[{}]", Thread.currentThread().getId(), letter));
                    // 释放下一个线程的许可
                    nextSemaphore.release();
                    ThreadUtil.safeSleep(1000);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
